package com.yq.servlet;



import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Enumeration;


@WebServlet("/ss1")
public class ServletDemo1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String realPath = getServletContext().getRealPath("");
        String filePath = realPath+"\\1.txt";
        FileOutputStream outputStream = new FileOutputStream(filePath);

        //请求行
        String method = req.getMethod();
        String requestURI = req.getRequestURI();
        String protocol = req.getProtocol();
        String line= method+" "+requestURI+" "+protocol;
        outputStream.write(line.getBytes());
        outputStream.write("\r\n".getBytes());

        //请求头
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String s = headerNames.nextElement();
            String header = req.getHeader(s);
            String headerOne = s+":" + header;
            outputStream.write(headerOne.getBytes());
            outputStream.write("\r\n".getBytes());

        }
        outputStream.write("\r\n".getBytes());

        // 请求体参数
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()){
            String s = parameterNames.nextElement();
            String parameter = req.getParameter(s);
            String paramOne = s+":"+parameter;
            outputStream.write(paramOne.getBytes());
            outputStream.write("\r\n".getBytes());

        }
        outputStream.close();

        resp.setContentType("text/html;charset=utf-8");

        resp.getWriter().println("htpp的请求参数已经保存到了"+filePath+"文件中！！");

    }
}
